package com.lanou3g.hw0517;

import com.lanou3g.hw0517.pojo.User;
import com.lanou3g.hw0517.util.JDBCUtil;
import com.lanou3g.hw0517.util.MyStatement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "resultServlet", urlPatterns = "/result")
public class resultServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String check1 = request.getParameter("check1");
        String check2 = request.getParameter("check2");
        String sql = "SELECT * FROM `users` WHERE username LIKE ? AND gender LIKE ?";
        MyStatement statement = JDBCUtil.getPreStatement(sql);
        statement.setString(1, "%" + check1 + "%");
        statement.setString(2, "%" + check2 + "%");
        ResultSet rs = statement.executeQuery();
        List<User> userList = new ArrayList<>();
        try {
            while (rs.next()) {
                User user = new User();
                String username = rs.getString("username");
                String password = rs.getString("pwd");
                String nickname = rs.getString("nickname");
                String hobby = rs.getString("hobby");
                String gender = rs.getString("gender");
                user.setUsername(username);
                user.setPwd(password);
                user.setNickname(nickname);
                user.setHobby(hobby);
                user.setGender(gender);
                userList.add(user);
            }
            request.setAttribute("users", userList);
            statement.close();
            rs.close();
            request.getRequestDispatcher("/user/result.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
